package com.rfid;

import android.content.Context;
import android.os.Handler;
import android.widget.Toast;

import com.rfid.sockethelper.ServerSocketHelper;
import com.rfid.sockethelper.SocketBase;
import com.rfid.udp.UdpManager;
import com.rfid.util.LogUtils;
import com.rfid.wlandirectlib.WifiDirectManager;
import com.rfid.wlandirectlib.WifiGroupListener;

public enum  DefaultServerManager implements SocketBase.OnReceiveListener{

    INSTANCE;

    Handler mHandler = new Handler();
    SocketBase.OnReceiveListener mOnReceiveListener;
    ServerSocketHelper helper;
    public void init(Context context) {
        helper = new ServerSocketHelper(this);
        UdpManager.getInstance().startBroadcastSelf("lw");
        int ret = WifiDirectManager.getInstance().initP2p(context);
        if (ret != 0) {
            Toast.makeText(context, "wifi直连初始化失败：" + ret, Toast.LENGTH_SHORT);
        }
        LogUtils.v("init ret = " + ret);
//        WifiDirectManager.getInstance().startDiscovery();
        if (ret == 0) {
            WifiDirectManager.getInstance().setGoupListener(new WifiGroupListener() {
                @Override
                public void onCreateGroup(boolean isSuccess) {
                    LogUtils.v("onCreateGroup " + isSuccess);
                }

                @Override
                public void onRemoveGroup(boolean isSuccess) {
                    LogUtils.v("onRemoveGroup " + isSuccess);
                }
            });
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    WifiDirectManager.getInstance().createGroup();
                }
            },200);
        }
    }


    public void setListener(SocketBase.OnReceiveListener listener) {
        mOnReceiveListener = listener;
    }


    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        if (mOnReceiveListener != null) {
            mOnReceiveListener.onReceived(ip,cmd,text);
        }
    }

    @Override
    public void onConnect(String ip, boolean connect) {
        if (mOnReceiveListener != null) {
            mOnReceiveListener.onConnect(ip,connect);
        }
    }

    public void destroy() {
        UdpManager.getInstance().destroy();
        helper.clear();
        WifiDirectManager.getInstance().removeGroup();
        WifiDirectManager.getInstance().destroy();
    }
}
